[id].tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /** @jsx h */
  2. /** @jsxFrag Fragment */
  3. import { Fragment, h } from "preact";
  4. import { Head } from "$fresh/runtime.ts";
  5. import { Handlers, PageProps } from "$fresh/server.ts";
  6. import { checkToken } from "utils/server.ts";
  7. import { find } from "utils/db.ts";
  8. import TopBar from "../../islands/TopBar.tsx";
  9. import Editor, { EditorMode } from "../../islands/Editor.tsx";
  10. interface PostProps {
  11. id: number;
  12. title: string;
  13. content: string;
  14. isLogined: boolean;
  15. allowMode: EditorMode;
  16. }
  17. export const handler: Handlers<PostProps> = {
  18. GET(req, ctx) {
  19. const tokenUserId = checkToken(req);
  20. const postId = Number(ctx.params.id);
  21. const post = find(
  22. "Post",
  23. tokenUserId
  24. ? {
  25. id: postId,
  26. user_id: tokenUserId,
  27. }
  28. : { id: postId, shared: true },
  29. ["title", "content"]
  30. );
  31. if (post.length > 0) {
  32. return ctx.render({
  33. id: postId,
  34. isLogined: Boolean(tokenUserId),
  35. allowMode: tokenUserId ? EditorMode.Both : EditorMode.Read,
  36. title: (post[0][0] as string) || "Untitled",
  37. content: post[0][1] as string,
  38. });
  39. }
  40. // Redirect to 404 page if not found
  41. return ctx.renderNotFound();
  42. },
  43. };
  44. export default function Post(props: PageProps) {
  45. return (
  46. <>
  47. <Head>
  48. <title>{props.data.title}</title>
  49. </Head>
  50. <div className="pd-page">
  51. <TopBar
  52. allowMode={props.data.allowMode}
  53. isLogined={props.data.isLogined}
  54. />
  55. <Editor
  56. id={props.data.id}
  57. title={props.data.title}
  58. content={props.data.content}
  59. allowMode={props.data.allowMode}
  60. />
  61. </div>
  62. </>
  63. );
  64. }